//
//  PublishImageViewController.m
//  InviteJob
//
//  Created by chirui on 2017/10/27.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "PublishImageViewController.h"
#import "PublsihAddressViewController.h"

@interface PublishImageViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UITextViewDelegate>{
    
    UITableView * _tableView;
    CGFloat heardHeight;
    
    UILabel * classLabel;
    UITextField * titleText;
    
    
    NSString * titleStr;
    NSString * contentStr;
    NSString * classStr;
    
    
    NSMutableArray * areaArray;
    NSMutableArray * codeArray; //编码带地址
    NSMutableArray * nameArray; //地址名称
    
    NSString *strAreLabel;
    UILabel *areLabel;
}

@end

@implementation PublishImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    titleStr= @"";
    contentStr = @"";
    classStr = @"";
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor =[UIColor whiteColor];
    areaArray = [NSMutableArray array];
    self.imageArray = [NSMutableArray array];
    TitleView(@"发布");
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(deledateSuccess:)
                                                 name: @"deledate"
                                               object:nil];

    [self creatTableView];
    heardHeight = 300;
    
//    /注册通知(等待接收消息)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addressChoose:) name:@"addressChoose" object:nil];
    
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)addressChoose:(NSNotification *)sender{
    //打印通知传过来的数值
    strAreLabel = sender.userInfo[@"addressChoose"];
    [_tableView reloadData];
}

-(void)deledateSuccess:(NSNotification *)notification{

    NSInteger i =  (self.imageArray.count/3);
    if (i>2) {
        i=2;
    }
    heardHeight = 170 + i*((WIDTH-32)/3) + (WIDTH-32)/3 + 6*(i+1);
    
    [_tableView reloadData];
}

-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor =strColor(@"f6f6f6");
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

     return 0.01;
  
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return heardHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
     return 200;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static  NSString * str = @"cellid";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
    
    if (cell==nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }else {
        while ([cell.contentView.subviews lastObject]!=nil) {
            [[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

        UIView * heardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, heardHeight)];
    
       for (UIView * view in heardView.subviews) {
        
        [view removeFromSuperview];
       }

        heardView.backgroundColor = [UIColor whiteColor];

    NSString *strType = USER_DEFAULTGet(@"server");
    NSString *strTitle;
    
    if ([strType isEqualToString:@"team"]) {
        strTitle = @"业务范围";
    }else{
        strTitle = @"业务需求";
    }
    
    [self creatNoNameLabelFrame:CGRectMake(10, 15,90, 20) andTextColor:[UIColor blackColor] andFount:15 andTextStr:strTitle andAlignment:NSTextAlignmentLeft onView:heardView];
    
    
    titleText =[[UITextField alloc]initWithFrame:CGRectMake(100, 15, WIDTH-110, 20)];
    titleText.placeholder = @"请输入标题";
    
    if (titleStr.length>0) {
        
        titleText.text = titleStr;
    }
    titleText.font =[UIFont systemFontOfSize:15];
    titleText.textAlignment = NSTextAlignmentRight;
    titleText.borderStyle = UITextBorderStyleNone;
    titleText.delegate = self;
    [heardView addSubview:titleText];
    
       [self creatLineViewFrame:CGRectMake(0, 50, WIDTH, 0.5) onView:heardView];
    
    
    self.contentTextView = [[SZTextView alloc]initWithFrame:CGRectMake(10, 70, WIDTH - 20, 95)];
    self.contentTextView.font = [UIFont systemFontOfSize:15];
    self.contentTextView.placeholder = @"请输入要发布的内容";
    
    if (contentStr.length>0) {
       self.contentTextView.text = contentStr;
    }
    
    self.contentTextView.delegate = self;
    [heardView addSubview:self.contentTextView];

    NSInteger i =  (self.imageArray.count/3);
    if (i>2) {
        i=2;
    }
    // 选择的图片
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    CGFloat margin = 6;
    CGFloat lenth = (WIDTH-20-margin*2)/3;
    flowLayout.itemSize = CGSizeMake(lenth, lenth);
    flowLayout.minimumLineSpacing = margin;
    flowLayout.minimumInteritemSpacing = margin;
    self.imageCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    self.imageCollectionView.backgroundColor = [UIColor whiteColor];
    self.imageCollectionView.scrollEnabled = NO;
    [heardView addSubview:self.imageCollectionView];
    [self.imageCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentTextView.mas_bottom).offset(10);
        make.left.equalTo(heardView).offset(10);
        make.right.equalTo(heardView).offset(-10);
        make.height.mas_equalTo(margin * 2 + lenth + lenth*i);
    }];
    // 代理&注册cell
    self.imageCollectionView.dataSource = self;
    self.imageCollectionView.delegate = self;
    [self.imageCollectionView registerClass:[ReleaseImageItemCell class] forCellWithReuseIdentifier:@"ReleaseImageItemCell"];
    
        return heardView;
}

-(void)textViewDidEndEditing:(UITextView *)textView{

    if ( self.contentTextView ==textView) {
        contentStr =  self.contentTextView.text;
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField{

    if ( titleText ==textField) {
        titleStr = titleText.text;
    }

}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    UIView * footerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    footerView.backgroundColor =[UIColor whiteColor];
    
    [self creatLineViewFrame:CGRectMake(0, 10, WIDTH, 0.5) onView:footerView];
    
    
    [self creatNoNameLabelFrame:CGRectMake(10, 25,WIDTH -30, 20) andTextColor:[UIColor blackColor] andFount:15 andTextStr:@"服务类型" andAlignment:NSTextAlignmentLeft onView:footerView];
    
    [self creatLineViewFrame:CGRectMake(0, 60, WIDTH, 0.5) onView:footerView];
    
    [self creatNoNameLabelFrame:CGRectMake(10, 75,WIDTH -30, 20) andTextColor:[UIColor blackColor] andFount:15 andTextStr:@"服务地区" andAlignment:NSTextAlignmentLeft onView:footerView];
    
    UIImageView * moreImage =[[UIImageView alloc]initWithFrame:CGRectMake(WIDTH -30, 20, 30, 30)];
    moreImage.image = ImageName(@"icon_user_list_more");
    [footerView addSubview:moreImage];
    UIImageView * more_twoImage =[[UIImageView alloc]initWithFrame:CGRectMake(WIDTH -30, 70, 30, 30)];
    more_twoImage.image = ImageName(@"icon_user_list_more");
    [footerView addSubview:more_twoImage];
    
     classLabel = [self creatLabelFrame:CGRectMake(100, 25, WIDTH -130, 20) andTextColor:[UIColor grayColor] andFount:15 andTextStr:classStr andAlignment:NSTextAlignmentRight onView:footerView];
    
    
    areLabel = [self creatLabelFrame:CGRectMake(100, 75, WIDTH -130, 20) andTextColor:[UIColor grayColor] andFount:15 andTextStr:strAreLabel andAlignment:NSTextAlignmentRight onView:footerView];
    
    UIButton * classbtn =[UIButton buttonWithType:UIButtonTypeCustom];
    classbtn.frame = CGRectMake(0, 10, WIDTH, 50);
    [classbtn addTarget:self action:@selector(classBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:classbtn];
    
    UIButton * arebtn =[UIButton buttonWithType:UIButtonTypeCustom];
    arebtn.frame = CGRectMake(0, 60, WIDTH, 50);
    [arebtn addTarget:self action:@selector(arebtnBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:arebtn];
    
    UIButton * endBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    endBtn.frame = CGRectMake(WIDTH/2-70, 140, 140, 35);
    endBtn.backgroundColor = NavBackColor;
    [endBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [endBtn setTitle:@"发布" forState:UIControlStateNormal];
    endBtn.layer.cornerRadius = 35/2.f;
    endBtn.layer.masksToBounds = YES;
    [footerView addSubview:endBtn];
    [endBtn addTarget:self action:@selector(publishClick:) forControlEvents:UIControlEventTouchUpInside];
     [self creatLineViewFrame:CGRectMake(0, 110, WIDTH, 0.5) onView:footerView];

    return footerView;
}

-(void)publishClick:(UIButton *)btn{

    if (titleText.text.length<=0||titleText.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请输入标题");
        return;
    }
    
    if (self.contentTextView.text.length<=0||self.contentTextView.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请输入发布内容");
        return;
    }
    if (classLabel.text.length<=0||classLabel.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请输入服务类型");
        return;
    }
    if (areaArray.count==0) {
        
        SHuiMBhudTextTimeStr(@"请选择服务地区");
        return;
    }
    
    if (self.imageArray.count>0) {
        
        [self upIconImageRequest];
    }else {
    
        [self noImageRequest];
    }

}

-(void)classBtnClick:(UIButton *)btn{
    
    NSArray *  titleArray = @[@"施工队",@"投标融资",@"设计外包",@"造价资料",
                              @"办营资安",@"证才中介",@"公司转让",@"教育培训",
                              @"建材供应",@"机械供应",@"二手租赁",@"房屋出租",
                              @"税法法务",@"维管后勤",@"特殊其他"];
    zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:titleArray andHeadTitle:@"服务类型" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
        classLabel.text  = choiceString ;
        
        classStr = choiceString;
        [pickerView dismissPicker];
    }];
    [pickerView show];
}

-(void)arebtnBtnClick:(UIButton *)btn{


    PublsihAddressViewController * publish = [[PublsihAddressViewController alloc]init];
    publish.block = ^(NSMutableArray * addressArray,NSMutableArray * addressNameArray,NSMutableArray * codeAndArray){
    
        areaArray = addressArray;
        nameArray = addressNameArray;
        codeArray = codeAndArray;
    };
    
    if (areaArray.count>0) {
        
        publish.meberNameArray = nameArray;
        publish.meberCodeArray = codeArray;
    }
    [self.navigationController pushViewController:publish animated:YES];
}

#pragma mark - 选择图片
// 配置图片选择器
- (void)configImageSelector {
    if(!self.imagePicker) {
        self.imagePicker = [[TZImagePickerController alloc]initWithMaxImagesCount:9 delegate:self];
        self.imagePicker.allowPreview = NO;
        self.imagePicker.alwaysEnableDoneBtn = YES;
        self.imagePicker.allowPickingOriginalPhoto = NO;
        self.imagePicker.allowPickingGif = NO;
        self.imagePicker.allowPickingVideo = NO;
        self.imagePicker.allowPickingImage = YES;
    }
    self.imagePicker.maxImagesCount = 9 - self.imageArray.count;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
    
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    [picker dismissViewControllerAnimated:YES completion:nil];
    // 获取图片
    for(UIImage *image in photos) {
        [self.imageArray addObject:image];
    }
    [self.imageCollectionView reloadData];
    
    NSInteger i =  (self.imageArray.count/3);
    if (i>2) {
        i=2;
    }

    heardHeight = 170 + i*((WIDTH-32)/3) + (WIDTH-32)/3 + 6*(i+1);
    
    [_tableView reloadData];
    
}
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - uicollectionview datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if(self.imageArray.count < 9) {
        return self.imageArray.count + 1;
    }else {
        return 9;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ReleaseImageItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ReleaseImageItemCell" forIndexPath:indexPath];
    // 配置添加照片按钮
    if(indexPath.item == self.imageArray.count) {
        [cell.cancelButton setHidden:YES];
        cell.imageView.image = [UIImage imageNamed:@"img_release_add"];
        return cell;
    }
    // 显示删除按钮
    [cell.cancelButton setHidden:NO];
    // 配置cell数据
    cell.indexPath = indexPath;
    cell.preVC = self;
    
    cell.imageView.image = self.imageArray[indexPath.item];
    
    return cell;
}

// 选中的item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.item == self.imageArray.count) {
        self.imagePicker = nil;
        [self configImageSelector];
    }
}
// 没有图片的
-(void)noImageRequest{
    
    NSString *strUrl = [NSString stringWithFormat:publish_service_api];
    isUser
    
    
    
    NSString * _strJsonProjectExperience;
    
    if (areaArray.count==0) {
        _strJsonProjectExperience = @"";
    }else{
        NSMutableArray *arrList = @[].mutableCopy;
        for (int i = 0; i <areaArray.count; i ++) {
            
            NSDictionary *dic = areaArray[i];
            
            [arrList addObject:[self ObjectTojsonString:dic]];
        }
        
        _strJsonProjectExperience =[NSString stringWithFormat:@"[%@]",[arrList componentsJoinedByString:@","]];
        
    }
    
    NSDictionary * dic = @{@"user_id":user.user_id,
                           @"token":user.token,
                           @"title":titleText.text,
                           @"service_describe":self.contentTextView.text,
                           @"service_type":classLabel.text,
                           @"area":_strJsonProjectExperience
                           };
    SHuiMBhubNoTimeStr(@"正在提交...");
    [PostNetWorking postNetWorkingStr:strUrl andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]== 200) {
            
            SHuiMBhudTextTimeStr(@"发布成功");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
         
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");    }];
    
}

// 有照片的
-(void)upIconImageRequest {
    
    NSString *strUrl = [NSString stringWithFormat:publish_service_api];
    isUser

    
    
    NSString * _strJsonProjectExperience;
    
    if (areaArray.count==0) {
        _strJsonProjectExperience = @"";
    }else{
        NSMutableArray *arrList = @[].mutableCopy;
        for (int i = 0; i <areaArray.count; i ++) {
          
            NSDictionary *dic = areaArray[i];
            
            [arrList addObject:[self ObjectTojsonString:dic]];
        }
        
        _strJsonProjectExperience =[NSString stringWithFormat:@"[%@]",[arrList componentsJoinedByString:@","]];
        
    }
    
    NSDictionary * dic = @{@"user_id":user.user_id,
                           @"token":user.token,
                           @"title":titleText.text,
                           @"service_describe":self.contentTextView.text,
                           @"service_type":classLabel.text,
                           @"area":_strJsonProjectExperience,
                           @"type":USER_DEFAULTGet(@"server")
                           };

    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    SHuiMBhubNoTimeStr(@"正在提交...");
    [manager POST:strUrl parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        for(int i = 0; i < self.imageArray.count; i++) {
            
            NSData *data = [(UIImage *)self.imageArray[i] compressToSize:300];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@%d.png", str,i];
            NSString * imageName = [NSString stringWithFormat:@"image%d",i];
            [formData appendPartWithFileData:data name:imageName fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            
            
            SHuiMBhudTextTimeStr(@"发布成功");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
        
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
        
    } ];
    
}





-(UILabel *)creatLabelFrame:(CGRect)rec andTextColor:(UIColor *)col andFount:(CGFloat)fount andTextStr:(NSString *)str andAlignment:(NSTextAlignment)alignment onView:(UIView *)view{
    
    UILabel * label =[[UILabel alloc]initWithFrame:rec];
    label.font =[UIFont systemFontOfSize:fount];
    label.textColor =col;
    label.text = str;
    label.textAlignment = alignment;
    [view addSubview:label];
    return label;
}

-(void)creatNoNameLabelFrame:(CGRect)rec andTextColor:(UIColor *)col andFount:(CGFloat)fount andTextStr:(NSString *)str andAlignment:(NSTextAlignment)alignment onView:(UIView *)view{
    
    UILabel * label =[[UILabel alloc]initWithFrame:rec];
    label.font =[UIFont systemFontOfSize:fount];
    label.textColor =col;
    label.text = str;
    label.textAlignment = alignment;
    [view addSubview:label];
}

-(void)creatTitleLabelFrame:(CGRect)rec andText:(NSString *)str onView:(UIView *)view{
    
    UILabel * tag_one =[[UILabel alloc]initWithFrame:rec];
    tag_one.font = [UIFont systemFontOfSize:16];
    tag_one.text = str;
    [view addSubview:tag_one];
}

-(void)creatLineViewFrame:(CGRect)rec onView:(UIView *)view{
    
    UIView * lineView = [[UIView alloc]initWithFrame:rec];
    lineView.backgroundColor = strColor(@"f6f6f6");
    [view addSubview:lineView];
}

-(NSString*)ObjectTojsonString:(id)object
{
    NSString *jsonString = [[NSString alloc]init];
    NSError *error;
    NSData *jsonData = [NSJSONSerialization  dataWithJSONObject:object  options:NSJSONWritingPrettyPrinted  error:&error];
    if (! jsonData) {
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"\n"  withString:@"" options:NSLiteralSearch range:range2];
    NSRange range3 = {0, mutStr.length};
    NSString * str = @"\\";
    [mutStr replaceOccurrencesOfString:str withString:@"" options:NSLiteralSearch range:range3];
    return mutStr;
}

@end
